package com.zzh.interview.service.impl;



import com.zzh.interview.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.zzh.interview.constant.UserConstant.USER_LOCK_CODE_EMAIL_KEY;


/**
 * @author 张 志 豪
 * @version 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Value("${spring.mail.username}")
    private String from;   // 邮件发送人

    @Resource
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean sendMsg(String to, String subject, String code) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);//头部头字段 (xxx登录系统注册验证码)
        String context = "";
        if (subject.contains("频繁")){//频繁访问，可能爬虫
            context = "有用户访问过于频繁了：" + code;
        }else {
            context = "验证码：" + code + " 一分钟内有效";
        }
        mailMessage.setText(context); //消息体 (xxx您的验证码是xxx)

        // 真正的发送邮件操作，从 from到 to
        try {
            mailSender.send(mailMessage);
        } catch (Exception e) {
            System.out.println("发送邮件出现异常: " + e.getMessage());
            return false;//表示发送失败(可能就是我们的邮箱不对！)
        }
        stringRedisTemplate.opsForValue().set(USER_LOCK_CODE_EMAIL_KEY+to,code,70, TimeUnit.SECONDS);//redis存储 70s
        return true;//表示发送成功
    }
}
